const msgType = {
	'-1':'text',
	0: 'text'
}

class Conversation {
	chatList = [];
	unreadCount = 0;
	limt = 20;
	page = 0;
	constructor() {}
	async getConversationCmdMethods(params, callback) {
		console.log(123465)
		const {
			data
		} = await uni.$Im.executeCmdMethods(23, params);
		this.set(data);
		callback && callback(data);
	}

	/**
	 * 生成会话id。
	 * @param {Object} callback
	 * 
	 */
	async generateConversationId(params, callback) {
		const {
			data
		} = await uni.$Im.executeCmdMethods(32, params);
		this.updateChatList(data)
		await this.getMessageList({
			"conversation": data.id,
			"maxTime": Date.now(),
			"offset": 1,
			"count": this.limt,
		});
		callback && callback(data);
	}

	/**
	 * 获取会话消息列表
	 * @param {{
				"conversation": data.id,
				"maxTime": Date.now(),
				"offset": 1,
				"count": 20,
			}} params
	 * @param {Object} callback
	 */
	async getMessageList(params, callback) {
		const {
			data
		} = await uni.$Im.executeCmdMethods(22, params);
		this.updateConversationMessageList(params.conversation, data);
		callback && callback(data);
	}

	mergeUniqueByProperty(arr1, arr2, prop) {
		const uniqueItems = arr2.filter(item =>
			arr1.findIndex(t => t[prop] === item[prop]) === -1
		);
		return [...uniqueItems, ...arr1];
	}


	updateConversationMessageList(id, data) {
		const target = this.chatList.find(item => item.id === id);
		if (target) {
			target.msgList = this.mergeUniqueByProperty(target.msgList, data, 'serviceCreateTime');
		}
	}

	getConversationMessageList(id, callback) {
		const target = this.chatList.find(item => item.id === id || item.groupId == id);
		return this.handleConversationMessageList(target?.msgList || []) ;
	}

	handleConversationMessageList(data) {
		return data.map(item => {
			return {
				"body": item.content,
				"type": msgType[item.msgType],
				"from_uid": item.from,
				"nickname": item.from,
				"to_uid": item.to,
				"is_read": false,
				"create_time": item.createTime,
				"update_time": item.serviceCreateTime,
				"conversation_id": item.conversation,
				"appid": "",
				"call_uid": [],
				// "reader_list": [{
				// 	"user_id": "676b81c9bb861798f102cf82",
				// 	"create_time": 1735403620423
				// }],
				"id": item.id,
				"_id": "",
				"unique_id": ""
			}
		})
	}

	/**
	 * 监听会话列表消息
	 */
	postConversationMessage() {
		uni.$Im.postMeassage(11, (res) => {
			const {
				data
			} = res;
			this.updateChatList(data);
		})
		//撤回消息
		uni.$Im.postMeassage(26, (res) => {
			const {
				data
			} = res;
			this.updateRevokeMsg(data);
		})
	}

	updateChatList(data) {
		const id = data.cmd == 11 || data.hasOwnProperty('groupId') ? (data.conversation ?? data.id)  : data.id;
		const target = this.getConversationById(id);
		if (target) {
			this.updateConversation(target, data)
		} else {
			this.createConversation(data);
		}
		this.getUnreadCount();
		this.set(this.sortByUpdateTime());
	}

	updateConversation(target, data) {
		let hasConversationId = uni.$Im.getCurrentConversationId();
		// if (hasConversationId == target.id) {
		if (data.cmd == 11) {
			target.unreadCount = !hasConversationId ? target.unreadCount++ : 0;
			target.lastMsgNote = data.content;
			target.updateTime = data.serviceCreateTime;
			target.msgList.push({
				"msgType": data.msgType,
				"createTime": data.serviceCreateTime,
				"msgState": data.msgState,
				"extras": data.extras,
				"from": data.from,
				"id": data.newConversationObj.id,
				"serviceCreateTime": data.serviceCreateTime,
				"to": data.to,
				"content": data.content,
				"conversation": data.conversation,
				"chatType": data.chatType,
				"extras0": '{}'
			});
		} else {
			target._updateTime = Date.now();
		}

		// }
	}

	//创建新一条的会话
	createConversation(data) {
		let reslut = {
			"extras": {},
			"unreadCount": data.unreadCount,
			"updateTime": Date.now(),
			"avatar": data.avatar,
			"id": data.id,
			"msgList": [

			],
			"friendUid": data.friendUid,
			"title": data.title,
			"type": data.type,
			"userId": uni.$Im.getCurrentUserId(),
			"lastMsgNote": '',
		}
		if(data.hasOwnProperty('groupId')){
			reslut.groupId = data.groupId
		}
		this.chatList.unshift(reslut)
	}

	//获取未读统计数量
	getUnreadCount() {
		const unreadCount = this.chatList.reduce((total, item) => {
			return total + item.unreadCount
		}, 0);

		this.updateUnreadCount(unreadCount);
		return unreadCount;
	}
	/**
	 * 更新未读数量
	 * @param {Number} unreadCount
	 */
	updateUnreadCount(unreadCount) {
		this.unreadCount = unreadCount;
	}

	/**
	 * 清除消息未读
	 * 
	 */
	async clearCurrentConversationUnreadCount(id) {
		const target = this.getConversationById(id);
		if (target) {
			target.unreadCount = 0;
		}
		const {
			data
		} = await uni.$Im.executeCmdMethods(33, {
			id,
			userId: uni.$Im.getCurrentUserId()
		});

		this.getUnreadCount();


	}
	/**
	 * 清除全部消息未读
	 * 
	 */
	clearAllUnreadCount() {
		this.chatList.forEach(item => {
			item.unreadCount = 0;
		})
		this.updateUnreadCount(0);
	}

	/**
	 * 
	 * 根据会话id获取会话信息
	 * @returns {Array}
	 */
	getConversationById(id) {
		return this.chatList.find(item => item.id === id || item.groupId === id);
	}

	/**
	 * 根据更新时间排序
	 * @returns {Array}
	 */
	sortByUpdateTime() {
		return this.chatList.sort((a, b) => b.updateTime - a._updateTime || a.updateTime);
	}
	/**
	 * 删除消息
	 * @param {Object} id
	 */
	async deleteMessage(params, callback) {
		const body = await uni.$Im.executeCmdMethods(45, params);
		const conversation = this.getConversationById(uni.$Im.getCurrentConversationId());
		const index = conversation.msgList.findIndex(item => item.id === params.msgId);
		if (index !== -1) {
			conversation.msgList.splice(index, 1);
		}
		callback && callback(data);
		return body.data;
	}
	/**
	 * 撤回消息
	 * @param {Object} id
	 * 
	 */
	async revokeMsg(params, callback) {
		const body = await uni.$Im.executeCmdMethods(46, params);
		// this.updateConversationMessageList(params.conversation, data);
		callback && callback(body.data);
		return body.data;
	}

	updateRevokeMsg(data) {
		const conversation = this.getConversationById(data.extras.conversation);
		const target = conversation.msgList.find(item => item.id === data.extras.messageId);
		target.content = data.content;
		target.createTime = data.createTime;
		target.serviceCreateTime = data.serviceCreateTime;
	}
	setLimt(limit) {
		this.limt = limit;
	}

	get(words) {
		if (words) {
			return this.chatList.filter(item => item.title.includes(words));
		} else {
			return this.chatList;
		}
	}

	set(data) {
		this.chatList = data;

		this.getUnreadCount();
	}
}

export default Conversation;